package com.xncoding.trans.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;

/**
 * MybatisPlus配置
 *
 * @author xiongneng
 * @since 2017/5/20 21:58
 */
@Configuration
@EnableTransactionManagement()
@MapperScan(basePackages = {"com.xncoding.trans.dao.repository"})
public class MybatisPlusConfig2 {

    @Resource
    private DruidProperties2 secondarydruidProperties;

    @Bean
    @ConfigurationProperties("spring.datasource.secondary")
    public DruidDataSource secondaryDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        secondarydruidProperties.config(dataSource);
        return dataSource;
    }
    @Bean
    public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DruidDataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setCacheEnabled(false);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }

    @Bean
    public PlatformTransactionManager secondaryTransactionManager(@Qualifier("secondaryDataSource") DruidDataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /***
     * sqlSessionTemplate与Spring事务管理一起使用，可以确保实际使用的 SqlSession 是与当前的 Spring 事务相关联的。这样，会话的生命周期（包括根据 Spring 的事务配置，在必要时关闭、提交或回滚会话）将由 Spring 管理
     */
    @Bean
    public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    /**
     * mybatis-plus分页插件
     */
    @Bean
    public PaginationInterceptor secondaryPaginationInterceptor() {
        return new PaginationInterceptor();
    }
}
